package com.aioething.iot.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.aioething.iot.dao.FirmwareDao;
import com.aioething.iot.dto.FirmwareDto;
import com.aioething.iot.model.Firmware;
import com.aioething.iot.service.IFirmwareService;
import com.aioething.iot.service.IOSSService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class FirmwareService implements IFirmwareService {
    @Autowired
    private FirmwareDao firmwareDao;
    @Autowired
    private IOSSService ossService;

    @Override
    public int save(Firmware firmware, MultipartFile file) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        Firmware exists = firmwareDao.selectByProductVersion(firmware.getProductId(), firmware.getVersion());
        if (ObjectUtil.isNotNull(exists))   throw new InternalException("固件已存在");
        // 上传文件
        String url = ossService.upload("config", file.getInputStream(), FileUtil.getSuffix(file.getOriginalFilename()));
        firmware.setUrl(url);
        firmware.setSize(file.getSize());
        firmware.setMd5(MD5.create().digestHex(file.getBytes()));
        return firmwareDao.insertSelective(firmware);
    }

    @Override
    public int delete(String firmwareId) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        Firmware firmware = firmwareDao.selectByPrimaryKey(firmwareId);
        if (ObjectUtil.isNull(firmware))    return 0;
        ossService.delete(firmware.getUrl());
        return firmwareDao.deleteByPrimaryKey(firmwareId);
    }

    @Override
    public PageInfo<Firmware> query(FirmwareDto firmwareDto) {
        PageHelper.startPage(firmwareDto.getPageNo(), firmwareDto.getPageSize());
        List<Firmware> list = firmwareDao.query(firmwareDto);
        return new PageInfo<>(list);
    }

    @Override
    public List<Firmware> list(FirmwareDto firmwareDto) {
        return firmwareDao.query(firmwareDto);
    }
}
